package com.singletonapps.evory.dao.impl;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.singletonapps.evory.dao.UserDao;
import com.singletonapps.evory.entities.User;

@Repository
public class UserDaoImpl implements UserDao {

	@Autowired
	private SessionFactory session;
	
	
	@Override
	public Long create(User user) {
		
		Long id = (Long) session.getCurrentSession().save(user);
		session.getCurrentSession().flush();
		
		return id;
	}
	

    @Override
    public User findUserByEmail(String email) {
        
        Query query = session.getCurrentSession().createQuery("FROM User u where u.email = :email");
        query.setParameter("email", email);
        
        return (User) query.uniqueResult();
        
    }


	@Override
	public User findUserByName(String userName) {
		
		Criteria criteria = session.getCurrentSession().createCriteria(User.class);
		criteria.add(Restrictions.eq("userName", userName));

		return (User) criteria.uniqueResult();
	}


	@Override
	public User findUserByUserNameOrEmail(String userName, String email) {
		
		Query query = session.getCurrentSession().createQuery("FROM User u WHERE u.userName = :userName OR u.email = :email");
		query.setParameter("userName", userName);
		query.setParameter("email", email);
        
        return (User) query.uniqueResult();
	}
	
	

}
